// ServiceCollectionExtensions.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;

namespace Beauty.Net.Kafka
{
    /// <summary>
    /// 服务注册扩展
    /// </summary>
    public static class KafkaServiceCollectionExtensions
    {
        /// <summary>
        /// 添加 Kafka 服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddKafka(this IServiceCollection services, Action<KafkaConfig> configureOptions)
        {
            var options = new KafkaConfig();
            configureOptions(options);
            services.AddSingleton(options);
            // 注册生产者
            services.TryAddSingleton<IKafkaProducer, KafkaProducer>();

            // 注册消费者
            services.TryAddSingleton<IKafkaConsumer, KafkaConsumer>();
            
            // 注册消费者工厂
            services.TryAddSingleton<IKafkaConsumerFactory, KafkaConsumerFactory>();

            return services;
        }
    }

    /// <summary>
    /// 消费者工厂接口
    /// </summary>
    public interface IKafkaConsumerFactory
    {
        /// <summary>
        /// 创建消费者
        /// </summary>
        /// <returns>消费者实例</returns>
        IKafkaConsumer CreateConsumer();
    }

    /// <summary>
    /// 消费者工厂实现
    /// </summary>
    public class KafkaConsumerFactory : IKafkaConsumerFactory
    {
        private readonly IServiceProvider _serviceProvider;

        public KafkaConsumerFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public IKafkaConsumer CreateConsumer()
        {
            return _serviceProvider.GetRequiredService<IKafkaConsumer>();
        }
    }
}
